package test;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;

import command.Command;

public class Server {

	public static int PORT = 12310;
	public static ServerSocket server = null;
	public static Socket connection = null;
	public static BufferedReader input = null;
	public static PrintWriter pw = null;
	public static ObjectOutputStream output = null;

	public static void start() {
		try {
			// 设定服务端的端口号
			server = new ServerSocket(PORT);
			System.out.println("ServerSocket Start:" + server);
			// 等待请求,此方法会一直阻塞,直到获得请求才往下走
			connection = server.accept();
			output = new ObjectOutputStream(connection.getOutputStream());
			System.out.println("Connection accept socket:" + connection);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void send(Command cmd) {
		System.out.println("server to send:" + cmd);
		if (connection != null && connection.isConnected()) {
			try {
				output.writeObject(cmd);
				output.flush();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}

	public static Object receive() {
		Object o = null;
		if (connection != null && connection.isConnected()) {
			try {
				input = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				ObjectInputStream is = new ObjectInputStream(
						new BufferedInputStream(connection.getInputStream()));
				while (true) {
					try {
						o = is.readObject();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						if(e instanceof java.lang.ClassNotFoundException){
							continue;
						}
						if(e instanceof java.net.SocketException){
							System.out.println(e.getMessage());
						}
						else{
							e.printStackTrace();
						}	
					}
					if (o != null) {
						System.out.println("server received object:" + o);
						return o;
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
				if(e instanceof java.net.SocketException){
					System.out.println(e.getMessage());
				}
				else{
					e.printStackTrace();
				}	
			}
		} else {
			System.out.println("Connection failed!");
		}
		return o;
	}
}
